/**
 winitTable组件模板
 调用方法：
 <winit-table thdata="info.thdata" page="info.page" is-check="info.check" data="info.dataModel"
 data-model="info.dataModel" find-blur="findInfo(info)" update-blur="update(info)" delete-blur="delete(info)"></winit-table>

 组件内格式说明：
 1.thdata：
 [{"thName":"操作","isSort":true},{"thName":"需求分析","isSort":false}]
 说明：thName=表头名称
 isSort=是否关闭排序 true：关闭，false：开启,默认开启
 2.page：;
 {"isTrue":true,"pageSize":10};
 说明：
 isTrue:是否使用分页
 pageSize:分页每页条数 不传默认30
 3.is-check=true
 说明：是否开启全选与多选选择,默认关闭
 4.data：
 基本参数={"isOperation":{"Find":{"isTrue":true,"msg":"查看"},"Update":{"isTrue":true,"msg":"更新"},"Delete":{"isTrue":false,"msg":"删除"}},"tdName":["id","email","contactType","name","language"]}
 说明：isOperation=操作功能：
 Find:isTrue是否开启查看按钮，msg:弹出框提示
 Update:isTrue是否开启修改按钮，msg:弹出框提示
 Delete:isTrue是否开启删除按钮，msg:弹出框提示
 tdName：对应的th下的td内容
 datas:通过查询接口查询的数据
 trIsClick:行是否可以点击
 5.find-blur，update-blur，delete-blur
 说明：查询，修改，删除按钮回调方法回调的数据为单行对象
 6.trcheck-blur
 说明：列表行点击事件点击后制灰并返回选中对象，返回对象中会增加trCheck选中为true
 7.isUserSearch
 是否要搜索框 true：要  不传不要

 */

angular.module('app').component('winitTable', {
    templateUrl: getTemplateUrl('matrix/component/tpl/winitTable.html'),
    bindings: {
        // value: '=', //这种输入必须用"json对象"作为输入,值改变后内外一起变.
        // title: '@', //这种输入必须用"string"作为输入.
        //title: '<', //这种输入必须用"json对象"作为输入, 而且内部修改内容后不影响外部
        // showList: '<',
        thdata: '<',
        // page: '=',
        isCheck: '@',//是否显示checkbox
        // isIndex: '=',
        data: '<',
        selected: '=?',
        hasSelected: '@',
        findBlur: '&',
        updateBlur: '&',
        deleteBlur: '&',
        trcheckBlur: '&',
        addBlur: '&',
        shareBlur: '&',
        isUserSearch: '@',
        viewBlur: '&',
        findTd: '&',
        viewPrototypeFun: '&',
        viewFeatureFun: '&',
        addBlur: '&',
        upBlur: '&',
        downBlur: '&',
        doneBlur: '&',
        ingBlur: '&',
        tableScope: '=',
        onlineFun: '&', // 上线方法
        tableHeight: '@',
        autoHeight: '@',
        tableId: '@',
        noLink: '@'
    },
    controller: function ($scope, $rootScope,$http, $interval, lodash, $filter, $timeout) {
        var ctrl = this;
        var headerHeight = 40;
        var footerHeight = 50;
        var rowHeight = 40;

        if (!ctrl.tableId) {
            ctrl.tableId = "tableId";
        }
        if (!ctrl.autoHeight) {
            ctrl.autoHeight = false;
        }
        if (!ctrl.tableHeight) {
            ctrl.tableHeight = 0;
        }
        if (ctrl.isCheck == undefined || ctrl.isCheck != "true") {
            ctrl.isCheck = false;
        } else {
            ctrl.isCheck = true;
        }

        ctrl.setTableHeight = function () {
            $timeout(function () {
                var divs = $(".dt")
                if(divs.length <= 0){
                    return
                }
                for (var i = 0; i < divs.length; i++) {
                    var div = $(".dt")[i]
                    var id = div.getAttribute("id");
                    var autoHeight = div.getAttribute("autoHeight");
                    var tableHeight = div.getAttribute("tableHeight");
                    if(!id){
                        continue
                    }
                    //autoHeight=true的div，自适应高度
                    if (autoHeight == 'true') {
                        var h = document.documentElement.clientHeight || document.body.clientHeight;
                        //框架头部、headerHeight、footerHeight
                        h = h - 60 - headerHeight - footerHeight - tableHeight;
                        $("#" + id).css("height", h + "px");
                    } else {
                        if (tableHeight == 0) {
                            $("#" + id).css("height", "350px");
                        } else {
                            $("#" + id).css("height", tableHeight + "px");
                        }
                    }
                }
            })
        }
        ctrl.setTableHeight();
        window.onresize = ctrl.setTableHeight;
        $scope.data = [];
        if (ctrl.tableScope != undefined) {
            ctrl.tableScope = $scope;
        }
        $scope.columnArray = [];

        var firstWidth = lodash.first(ctrl.thdata).width ? lodash.first(ctrl.thdata).width : 200;

        var firstTd = {
            name: lodash.first(ctrl.thdata).thName,
            prop: lodash.first(ctrl.data.tdName).name,
            flexGrow: 2,
            // template: '<span>{{$cell}}</span>',
            isCheckboxColumn: ctrl.isCheck,
            headerCheckbox: ctrl.isCheck,
            index: 0,
            width: firstWidth,
            cellRenderer: function () {
                return '<a href="javascript:void(0);" ng-click="onRowClick($row)">{{$cell}}</a>';
            }
        };
         var noLinkFirstTd = {
            name: lodash.first(ctrl.thdata).thName,
            prop: lodash.first(ctrl.data.tdName).name
         }
        $scope.columnArray.push(ctrl.noLink == "true" ? noLinkFirstTd : firstTd);

        angular.forEach(ctrl.thdata, function (th, thindex) {
            var tdItem = {name: '', prop: '', flexGrow: 1};
            if (!th.isHide) {
                if (thindex > 0) {
                    tdItem.name = th.thName;
                    tdItem.index = thindex;
                    tdItem.width = th.width ? th.width : 100;
                    angular.forEach(ctrl.data.tdName, function (td, tdindex) {
                        if (thindex == tdindex) {
                            tdItem.prop = td.name;
                        }
                    });
                    $scope.columnArray.push(tdItem);
                }
            }
        });

        var btnList = '<i class="glyphicon glyphicon-info-sign" style="margin-left: 10px;" popover="{{$ctrl.data.isOperation.Find.msg}}" popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.data.isOperation.Find.isTrue" ng-click="$ctrl.findByInfo($row)"></i>' +
            '<i class="glyphicon glyphicon-edit" popover="{{$ctrl.data.isOperation.Update.msg}}" style="margin-left: 10px;" popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.data.isOperation.Update.isTrue" ng-click="$ctrl.update($row)"></i>' +
            '<i class="icon-share" style="margin-left: 10px;" popover="{{$ctrl.data.isOperation.Share.msg}}" popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.data.isOperation.Share.isTrue" ng-click="$ctrl.share($row)"></i>' +
            '<i class="fa fa-tasks" style="margin-left: 10px;" popover="{{$ctrl.data.isOperation.view.msg}}" popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.data.isOperation.view.isTrue && $row.needId" ng-click="$ctrl.viewByInfo($row)"></i>' +
            '<i class="fa fa-cogs" style="margin-left: 10px;" popover="{{$ctrl.data.isOperation.viewFeature.msg}}" popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.data.isOperation.viewFeature.isTrue" ng-click="$ctrl.viewFeature($row)"></i>' +
            '<i class="fa fa-plus" style="margin-left: 10px;" popover="{{$ctrl.data.isOperation.add.msg}}" popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.data.isOperation.add.isTrue" ng-click="$ctrl.add($row)"></i>' +
            '<i class="fa fa-arrow-up" style="margin-left: 10px;" popover="{{$ctrl.data.isOperation.up.msg}}" popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.data.isOperation.up.isTrue" ng-click="$ctrl.up($row)"></i>' +
            '<i class="fa fa-arrow-down" style="margin-left: 10px;" popover="{{$ctrl.data.isOperation.down.msg}}" popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.data.isOperation.down.isTrue" ng-click="$ctrl.down($row)"></i>' +
            '<i class="fa fa-arrow-circle-up" style="margin-left: 10px;" popover="{{$ctrl.data.isOperation.Online.msg}}" popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.canOperate() && $ctrl.data.isOperation.Online.isTrue" ng-click="$ctrl.online($row)"></i>' +
            '<i class="fa fa-check-circle-o" style="margin-left: 10px;font-size: 15px;" popover="{{$ctrl.data.isOperation.Complete.msg}}" popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.data.isOperation.Complete.isTrue" ng-click="$ctrl.done($row)"></i>' +
            '<i class="fa fa-clock-o" style="margin-left: 10px;font-size: 15px;" popover="{{$ctrl.data.isOperation.Ing.msg}}" popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.data.isOperation.Ing.isTrue" ng-click="$ctrl.ing($row)"></i>'+
            '<i class="fa fa-remove" style="margin-left: 10px;" popover="{{$ctrl.data.isOperation.Delete.msg}}"  popover-trigger="mouseenter" popover-placement="left" ng-if="$ctrl.data.isOperation.Delete.isTrue" ng-click="$ctrl.delete($row)"></i>' ;
        var lastTd = {
            name: "操作", flexGrow: 1, index: $scope.columnArray.length,
            cellRenderer: function () {
                return btnList;
            }
        };

        var lastTh = lodash.last(ctrl.thdata);
        if (!lastTh.isHide) {
            $scope.columnArray.push(lastTd);
        }

        $scope.all = angular.copy($scope.columnArray);

        $scope.cur = angular.copy($scope.columnArray);

        $scope.options = {
            rowHeight: rowHeight,
            headerHeight: headerHeight,
            footerHeight: footerHeight,
            checkboxSelection: true,
            selectable: true,
            multiSelect: true,
            columnMode: 'force',
            emptyMessage: '暂无数据！',
            columns: $scope.cur
        };

        $scope.selected = [];

        ctrl.selected = $scope.selected;

        $scope.$watch('selected', function (newVal) {
            ctrl.selected = $scope.selected;
        }, true)

        $scope.onSelect = function (rows) {
            rows[0].check = true;
            if (ctrl.hasSelected == "true") {
                // ctrl.selected = rows;
                ctrl.selected = $scope.selected;
            }
        };

        angular.forEach($scope.all, function (all) {
            angular.forEach($scope.cur, function (cur) {
                if (all.prop == cur.prop) {
                    all.checked = true;
                }
            });
        });

        $scope.onCheck = function (col) {
            var colIndex = lodash.findIndex($scope.cur, function (cur) {
                return cur.name == col.name;
            });
            if (colIndex == -1) {
                col.checked = true;
                $scope.cur.push(col);
                $scope.options.columns = $filter('orderBy')($scope.cur, "index", false);
            } else {
                col.checked = false;
                lodash.remove($scope.cur, {"name": col.name});
                $scope.options.columns = $filter('orderBy')($scope.cur, "index", false);
            }
        }

        $scope.stop = function ($event) {
            $event.stopPropagation();
        };

        $scope.onRowClick = function (row) {
            ctrl.findTd({
                info: row
            })
        };

        ctrl.isCheckAll = false;
        ctrl.addIsTrue = false;
        ctrl.timer = null;
        ctrl.showOperater = false;
        if (ctrl.data) {
            angular.forEach(ctrl.data.isOperation, function (key, value) {
                if (key.isTrue) {
                    ctrl.showOperater = true;
                }
            });
        }

        $scope.data = ctrl.data;

        $scope.$watch("data", function (newVal) {
            if (ctrl.data.datas) {
                $scope.datas = ctrl.data.datas;
                ctrl.setTableHeight();
            }
        }, true)

        ctrl.$onInit = function () {
        }

        // ctrl.$onChanges = function () {
        //     console.log("xxxxxx")
        //     console.log(ctrl.data)
        //     $scope.datas = ctrl.data.datas;
        //     ctrl.setTableHeight();
        // }

        ctrl.$onDestroy = function () {
            if (ctrl.timer != null) {
                $interval.cancel(ctrl.timer);
            }
        }

        //查询单条事件
        ctrl.findByInfo = function (info) {
            ctrl.findBlur({
                info: info
            });
        };
        ctrl.viewByInfo = function (info) {
            ctrl.viewBlur({
                info: info
            });
        };
        //更新时间
        ctrl.update = function (info) {
            ctrl.updateBlur({
                info: info
            });
        };
        //删除事件
        ctrl.delete = function (info) {
            ctrl.deleteBlur({
                info: info
            });
        };
        ctrl.share = function (info) {
            ctrl.shareBlur({
                info: info
            });
        };
        ctrl.viewFeature = function (info) {
            ctrl.viewFeatureFun({
                info: info
            });
        };
        ctrl.online = function (info) {
            ctrl.onlineFun({
                info: info
            });
        };
        ctrl.add = function (info) {
            ctrl.addBlur({
                info: info
            });
        };
        ctrl.up = function (info) {
            ctrl.upBlur({
                info: info
            });
        };
        ctrl.down = function (info) {
            ctrl.downBlur({
                info: info
            });
        };
        ctrl.done = function (info) {
            ctrl.doneBlur({
                info: info
            });
        };
        ctrl.ing = function (info) {
            ctrl.ingBlur({
                info: info
            });
        };
        ctrl.canOperate = function () {
            return $rootScope.isUserCanOperateByRole();
        };
    }

})